package com.budwk.app.jim.client;

import cn.hutool.core.text.StrFormatter;
import org.jim.client.handler.ImClientHandler;
import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.config.ImConfig;
import org.jim.core.exception.ImDecodeException;
import org.jim.core.exception.ImException;
import org.jim.core.packets.Command;
import org.jim.core.tcp.TcpPacket;
import org.jim.core.tcp.TcpServerDecoder;
import org.jim.core.tcp.TcpServerEncoder;

import java.nio.ByteBuffer;

/**
 * @author ZY.Wang
 * @since 2023/6/15
 */
public class JimImClientHandler implements ImClientHandler, ImConst {

    private static final TcpPacket heartbeatPacket = new TcpPacket(Command.COMMAND_HEARTBEAT_REQ,new byte[]{Protocol.HEARTBEAT_BYTE});

    @Override
    public ImPacket heartbeatPacket(ImChannelContext imChannelContext) {
        return heartbeatPacket;
    }

    @Override
    public ImPacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ImChannelContext imChannelContext) throws ImDecodeException, ImDecodeException {
        return TcpServerDecoder.decode(buffer, imChannelContext);
    }

    @Override
    public ByteBuffer encode(ImPacket imPacket, ImConfig imConfig, ImChannelContext imChannelContext) {
        TcpPacket tcpPacket = (TcpPacket)imPacket;
        return TcpServerEncoder.encode(tcpPacket, imConfig, imChannelContext);
    }

    @Override
    public void handler(ImPacket imPacket, ImChannelContext imChannelContext) throws ImException {
        TcpPacket helloPacket = (TcpPacket) imPacket;
        byte[] body = helloPacket.getBody();
        if (body != null) {
            try {
                String str = new String(body, ImConst.CHARSET);
                System.out.println(StrFormatter.format("客户端收到消息:{}", str));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
